package com.zzk.rxjavamvvm.app;

import android.annotation.SuppressLint;
import android.app.Application;

import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.zzk.rxjavamvvm.data.DemoRepository;
import com.zzk.rxjavamvvm.ui.login.LoginViewModel;
import com.zzk.rxjavamvvm.ui.network.NetWorkViewModel;

/**
 * activity堆栈式管理
 *
 * @ProjectName: RXMVVMBase
 * @Package: com.zzk.rxmvvmbase
 * @ClassName:
 * @Description:
 * @Author: brilliantzhao
 * @CreateDate: 2021.1.13 10:12
 * @UpdateUser:
 * @UpdateDate: 2021.1.13 10:12
 * @UpdateRemark:
 * @Version: 1.0.0
 */
public class AppViewModelFactory extends ViewModelProvider.NewInstanceFactory {

    @SuppressLint("StaticFieldLeak")
    private static volatile AppViewModelFactory INSTANCE;
    private final Application mApplication;
    private final DemoRepository mRepository;

    public static AppViewModelFactory getInstance(Application application) {
        if (INSTANCE == null) {
            synchronized (AppViewModelFactory.class) {
                if (INSTANCE == null) {
                    INSTANCE = new AppViewModelFactory(application, Injection.provideDemoRepository());
                }
            }
        }
        return INSTANCE;
    }

    @VisibleForTesting
    public static void destroyInstance() {
        INSTANCE = null;
    }

    private AppViewModelFactory(Application application, DemoRepository repository) {
        this.mApplication = application;
        this.mRepository = repository;
    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        if (modelClass.isAssignableFrom(NetWorkViewModel.class)) {
            return (T) new NetWorkViewModel(mApplication, mRepository);
        } else if (modelClass.isAssignableFrom(LoginViewModel.class)) {
            return (T) new LoginViewModel(mApplication, mRepository);
        }
        throw new IllegalArgumentException("Unknown ViewModel class: " + modelClass.getName());
    }
}
